import React, { useState, useEffect } from 'react';

// 动态计算后端 API 的基地址
const getApiBaseUrl = () => {
  const protocol = window.location.protocol;
  const hostname = window.location.hostname;
  const backendPort = 5000;
  return `${protocol}//${hostname}:${backendPort}`;
};
const API_BASE_URL = getApiBaseUrl();

function NodeModal({ selectedNode, updateNodeData, closeModal, allNodes, edges }) {
  const [nodeData, setNodeData] = useState(selectedNode?.data || {});
  const [nodeName, setNodeName] = useState(selectedNode?.data?.name || '');
  const [variables, setVariables] = useState(selectedNode?.data?.variables || {});
  const [outputVar, setOutputVar] = useState(selectedNode?.data?.output_var || '');
  const [tempVarNames, setTempVarNames] = useState({});
  const [uploadStatus, setUploadStatus] = useState({});
  const [inputVariables, setInputVariables] = useState(selectedNode?.data?.inputVariables || {});
  const [newVarName, setNewVarName] = useState('');
  const [knowledgeBases, setKnowledgeBases] = useState([]);
  const [headers, setHeaders] = useState(() => {
    try {
      return JSON.parse(nodeData.headers || '{}');
    } catch (e) {
      return {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer <token_placeholder>'
      };
    }
  });
  const [newHeaderKey, setNewHeaderKey] = useState('');
  const [newHeaderValue, setNewHeaderValue] = useState('');

  useEffect(() => {
    const data = selectedNode?.data || {};
    setNodeData(data);
    setNodeName(data.name || '');
    setVariables(data.variables || {});
    setOutputVar(data.output_var || '');
    setTempVarNames(
      Object.keys(data.variables || {}).reduce((acc, key) => {
        acc[key] = key;
        return acc;
      }, {})
    );
    setUploadStatus({});
    if (data.nodeType === 'code') {
      setInputVariables(data.inputVariables || {});
    } else {
      setInputVariables({});
    }
    setNewVarName('');
    try {
      setHeaders(JSON.parse(data.headers || '{}'));
    } catch (e) {
      setHeaders({
        'Content-Type': 'application/json',
        'Authorization': 'Bearer <token_placeholder>'
      });
    }
    if (data.nodeType === 'knowledge') {
      fetch(`${API_BASE_URL}/knowledge-bases`)
        .then(res => {
          if (!res.ok) throw new Error('Network response was not ok');
          return res.json();
        })
        .then(data => setKnowledgeBases(data))
        .catch(err => {
          console.error("Failed to fetch knowledge bases:", err);
          setKnowledgeBases([]);
        });
    }
  }, [selectedNode]);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setNodeData((prev) => ({ ...prev, [name]: value }));
  };

  const handleKnowledgeBaseChange = (e) => {
    const selectedId = e.target.value;
    const selectedKb = knowledgeBases.find(kb => kb.id === selectedId);
    setNodeData(prev => ({
      ...prev,
      knowledge_base_id: selectedId,
      knowledge_base_name: selectedKb ? selectedKb.name : ''
    }));
  };

  const handleNameChange = (e) => {
    setNodeName(e.target.value);
  };

  const handleVariableChange = (key, value, type = null, displayName = null) => {
    setVariables((prev) => {
      const currentVar = prev[key] || {};
      const newType = type !== null ? type : currentVar.type;
      const newValue = value;
      const newDisplayName = displayName !== null ? displayName : currentVar.displayName;
      return {
        ...prev,
        [key]: { 
          value: newValue, 
          type: newType,
          ...(newDisplayName && (newType === 'image' || newType === 'video') && { displayName: newDisplayName })
        }
      };
    });
  };

  const handleVariableNameChange = (oldKey, newName) => {
    setTempVarNames((prev) => ({ ...prev, [oldKey]: newName }));
  };

  const confirmVariableNameChange = (oldKey) => {
    const newKey = tempVarNames[oldKey]?.trim();
    if (newKey && newKey !== oldKey && !Object.keys(variables).includes(newKey)) {
      setVariables((prev) => {
        const updated = { ...prev };
        const value = updated[oldKey];
        delete updated[oldKey];
        updated[newKey] = value;
        return updated;
      });
      setTempVarNames((prev) => {
        const updated = { ...prev };
        delete updated[oldKey];
        updated[newKey] = newKey;
        return updated;
      });
    } else if (newKey === '') {
      removeVariable(oldKey);
    }
  };

  const handleVariableNameKeyPress = (e, oldKey) => {
    if (e.key === 'Enter') {
      confirmVariableNameChange(oldKey);
      e.target.blur();
    }
  };

  const addVariable = (selectedOutputVar = null) => {
    const nodeType = selectedNode.data.nodeType;
    const newKey = selectedOutputVar || `var_${Object.keys(variables).length + 1}`;
    setVariables((prev) => ({
      ...prev,
      [newKey]: nodeType === 'start' ? { value: '', type: 'text' } : newKey
    }));
    setTempVarNames((prev) => ({ ...prev, [newKey]: newKey }));
  };

  const removeVariable = (key) => {
    setVariables((prev) => {
      const updated = { ...prev };
      delete updated[key];
      return updated;
    });
    setTempVarNames((prev) => {
      const updated = { ...prev };
      delete updated[key];
      return updated;
    });
  };

  const handleFileUpload = async (e, key) => {
    const file = e.target.files[0];
    if (!file) return;
    setUploadStatus(prev => ({ ...prev, [key]: '上传中...' }));
    const formData = new FormData();
    formData.append('file', file);
    try {
      const response = await fetch(`${API_BASE_URL}/upload-file`, {
        method: 'POST',
        body: formData,
      });
      const result = await response.json();
      if (response.ok) {
        handleVariableChange(key, result.url, null, file.name);
        setUploadStatus(prev => ({ ...prev, [key]: '上传成功!' }));
      } else {
        setUploadStatus(prev => ({ ...prev, [key]: `上传失败: ${result.error}` }));
      }
    } catch (error) {
      setUploadStatus(prev => ({ ...prev, [key]: `网络错误: ${error.message}` }));
    }
  };

  const addHeader = () => {
    if (newHeaderKey && newHeaderValue) {
      setHeaders((prev) => ({
        ...prev,
        [newHeaderKey]: newHeaderValue,
      }));
      setNewHeaderKey('');
      setNewHeaderValue('');
    }
  };

  const removeHeader = (key) => {
    setHeaders((prev) => {
      const newHeaders = { ...prev };
      delete newHeaders[key];
      return newHeaders;
    });
  };

  const handleKeyChange = (e) => setNewHeaderKey(e.target.value);
  const handleValueChange = (e) => setNewHeaderValue(e.target.value);

  const addCodeInputVariable = () => {
    if (newVarName.trim() && !inputVariables[newVarName.trim()]) {
      setInputVariables(prev => ({
        ...prev,
        [newVarName.trim()]: ''
      }));
      setNewVarName('');
    } else {
      alert("请输入一个唯一的、不为空的参数名称。");
    }
  };

  const handleUpstreamVarChange = (key, value) => {
    setInputVariables(prev => ({
      ...prev,
      [key]: value
    }));
  };

  const removeCodeInputVariable = (key) => {
    setInputVariables(prev => {
      const updated = { ...prev };
      delete updated[key];
      return updated;
    });
  };

  const handleSubmit = () => {
    if (selectedNode) {
      Object.keys(tempVarNames).forEach((oldKey) => confirmVariableNameChange(oldKey));
      updateNodeData(selectedNode.id, { 
        ...nodeData, 
        name: nodeName, 
        variables, 
        output_var: outputVar, 
        headers: JSON.stringify(headers),
        ...(selectedNode.data.nodeType === 'code' && { inputVariables })
      });
      closeModal();
    }
  };

  const handleDelete = () => {
    if (selectedNode) {
      updateNodeData(selectedNode.id, {}, true);
      closeModal();
    }
  };

  const currentNodeBackendType = selectedNode.data.nodeType;

  const getUpstreamOutputVars = (restrictTypes = [], restrictToStartNode = false) => {
    const upstreamNodeIds = new Set();
    const visited = new Set();
    const collectUpstreamNodes = (nodeId) => {
      if (visited.has(nodeId)) return;
      visited.add(nodeId);
      const incomingEdges = edges.filter((edge) => edge.target === nodeId);
      incomingEdges.forEach((edge) => {
        upstreamNodeIds.add(edge.source);
        collectUpstreamNodes(edge.source);
      });
    };
    collectUpstreamNodes(selectedNode.id);
    const upstreamNodes = allNodes.filter((node) => upstreamNodeIds.has(node.id));
    let outputVars = [];
    upstreamNodes.forEach((node) => {
      if (restrictToStartNode && node.data.nodeType !== 'start') return;
      if (node.data.nodeType === 'start') {
        Object.entries(node.data.variables || {}).forEach(([key, { type }]) => {
          if (!restrictTypes.length || restrictTypes.includes(type)) {
            outputVars.push(key);
          }
        });
      } else if (!restrictToStartNode && node.data.output_var) {
        outputVars.push(node.data.output_var);
      }
    });
    return [...new Set(outputVars)];
  };

  const previousOutputVars = getUpstreamOutputVars();
  const mediaOutputVars = getUpstreamOutputVars(['image', 'video'], true);

  const renderNodeSpecificFields = () => {
    switch (currentNodeBackendType) {
      case 'start':
        return (
          <>
            <label className="block mb-2 text-sm font-medium text-gray-700">变量:</label>
            {Object.entries(variables).map(([key, { value, type, displayName }]) => (
              <div key={key} className="flex flex-col gap-2 mb-3 p-3 border rounded-md bg-gray-50">
                <div className="flex items-center gap-2">
                  <input
                    type="text"
                    value={tempVarNames[key] || ''}
                    onChange={(e) => handleVariableNameChange(key, e.target.value)}
                    onBlur={() => confirmVariableNameChange(key)}
                    onKeyPress={(e) => handleVariableNameKeyPress(e, key)}
                    className="w-1/3 p-2 border border-gray-300 rounded-md"
                    placeholder="变量名"
                  />
                  <select
                    value={type}
                    onChange={(e) => handleVariableChange(key, value, e.target.value, displayName)}
                    className="w-1/3 p-2 border border-gray-300 rounded-md"
                  >
                    <option value="text">文本</option>
                    <option value="document">文档</option>
                    <option value="image">图片</option>
                    <option value="video">视频</option>
                  </select>
                  <button
                    onClick={() => removeVariable(key)}
                    className="px-2 py-1 bg-red-500 text-white rounded-md hover:bg-red-600"
                  >
                    删除
                  </button>
                </div>
                <div className="mt-2 flex items-center gap-2">
                  <input
                    type="text"
                    value={(type === 'image' || type === 'video') && displayName ? displayName : value}
                    onChange={(e) => handleVariableChange(key, e.target.value, type, displayName)}
                    className="flex-grow p-2 border border-gray-300 rounded-md"
                    placeholder={
                      (type === 'image' || type === 'video')
                        ? "粘贴URL或点击右侧上传"
                        : "变量值 (支持 {{var}} 引用)"
                    }
                  />
                  {(type === 'image' || type === 'video') && (
                    <label className="cursor-pointer px-3 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 shrink-0">
                      上传
                      <input
                        type="file"
                        className="hidden"
                        accept={type === 'image' ? 'image/*' : 'video/*'}
                        onChange={(e) => handleFileUpload(e, key)}
                      />
                    </label>
                  )}
                </div>
                {uploadStatus[key] && <p className="text-xs text-gray-600 mt-1">{uploadStatus[key]}</p>}
              </div>
            ))}
            <button
              onClick={() => addVariable()}
              className="px-3 py-2 mt-2 bg-green-500 text-white rounded-md hover:bg-green-600"
            >
              新增变量
            </button>
          </>
        );
      case 'end':
        return (
          <>
            <label className="block mb-2 text-sm font-medium text-gray-700">输入变量:</label>
            {Object.keys(variables).map((key) => (
              <div key={key} className="flex gap-2 mb-2">
                <input
                  type="text"
                  value={key}
                  readOnly
                  className="w-2/3 p-2 border border-gray-300 rounded-md bg-gray-100"
                />
                <button
                  onClick={() => removeVariable(key)}
                  className="px-2 py-1 bg-red-500 text-white rounded-md hover:bg-red-600"
                >
                  删除
                </button>
              </div>
            ))}
            <div className="flex gap-2 mt-2">
              <select
                onChange={(e) => e.target.value && addVariable(e.target.value)}
                className="w-full p-2 border border-gray-300 rounded-md"
                value=""
              >
                <option value="">选择已有变量</option>
                {previousOutputVars.map((varName, index) => (
                  <option key={index} value={varName}>
                    {varName}
                  </option>
                ))}
              </select>
            </div>
          </>
        );
      case 'llm':
        return (
          <>
            <label className="block mb-2 text-sm font-medium text-gray-700">模型URL:</label>
            <input
              type="text"
              name="model_url"
              value={nodeData.model_url || ''}
              onChange={handleChange}
              className="w-full p-2 border border-gray-300 rounded-md"
              placeholder="例如: https://dashscope.aliyuncs.com/compatible-mode/v1"
            />
            <label className="block mt-3 mb-2 text-sm font-medium text-gray-700">模型名称:</label>
            <input
              type="text"
              name="model_name"
              value={nodeData.model_name || ''}
              onChange={handleChange}
              className="w-full p-2 border border-gray-300 rounded-md"
              placeholder="例如: qwen-vl-max-latest"
            />
            <label className="block mt-3 mb-2 text-sm font-medium text-gray-700">API Key:</label>
            <input
              type="text"
              name="api_key"
              value={nodeData.api_key || ''}
              onChange={handleChange}
              className="w-full p-2 border border-gray-300 rounded-md"
              placeholder="例如: sk-xxx"
            />
            <label className="block mt-3 mb-2 text-sm font-medium text-gray-700">媒体变量（图片/视频，可选）:</label>
            <select
              name="video_url"
              value={nodeData.video_url || ''}
              onChange={handleChange}
              className="w-full p-2 border border-gray-300 rounded-md"
            >
              <option value="">选择图片或视频变量</option>
              {mediaOutputVars.length > 0 ? (
                mediaOutputVars.map((varName, index) => (
                  <option key={index} value={varName}>
                    {varName}
                  </option>
                ))
              ) : (
                <option value="" disabled>
                  无可用图片或视频变量
                </option>
              )}
            </select>
            <p className="text-xs text-gray-500 mt-2">
              选择开始节点定义的图片或视频变量，例如“v_url”。确保变量名与上下文中的键名一致。
            </p>
            <label className="block mt-3 mb-2 text-sm font-medium text-gray-700">System 提示词:</label>
            <textarea
              name="system"
              value={nodeData.system || ''}
              onChange={handleChange}
              className="w-full p-2 border border-gray-300 rounded-md font-mono"
              placeholder="例如: 你是一个专业的分析助手，可使用 {{variable}} 引用上下文变量，例如 {{v_url}}。"
              rows="4"
            />
            <label className="block mt-3 mb-2 text-sm font-medium text-gray-700">User 提示词:</label>
            <textarea
              name="user"
              value={nodeData.user || ''}
              onChange={handleChange}
              className="w-full p-2 border border-gray-300 rounded-md font-mono"
              placeholder="例如: 分析 {{v_url}} 的内容，可使用 {{variable}} 引用上下文变量，例如 {{v_url}}。"
              rows="4"
            />
          </>
        );
      case 'branch':
        return (
          <>
            <label className="block mb-2 text-sm font-medium text-gray-700">IF 条件:</label>
            <div className="flex gap-2 mb-2">
              <select
                value={nodeData.variable || ''}
                onChange={(e) => handleChange({ target: { name: 'variable', value: e.target.value } })}
                className="w-1/3 p-2 border border-gray-300 rounded-md"
              >
                <option value="">选择变量</option>
                {previousOutputVars.map((varName, index) => (
                  <option key={index} value={varName}>{varName}</option>
                ))}
              </select>
              <select
                value={nodeData.conditionType || ''}
                onChange={(e) => handleChange({ target: { name: 'conditionType', value: e.target.value } })}
                className="w-1/3 p-2 border border-gray-300 rounded-md"
              >
                <option value="">选择条件</option>
                <option value="contains">包含</option>
                <option value="not_contains">不包含</option>
                <option value="starts_with">开始是</option>
                <option value="ends_with">结束是</option>
                <option value="equals">等于</option>
                <option value="not_equals">不等于</option>
                <option value="is_empty">为空</option>
                <option value="is_not_empty">不为空</option>
              </select>
              <input
                type="text"
                value={nodeData.conditionValue || ''}
                onChange={(e) => handleChange({ target: { name: 'conditionValue', value: e.target.value } })}
                className="w-1/3 p-2 border border-gray-300 rounded-md"
                placeholder="值"
              />
            </div>
            <p className="text-xs text-gray-500 mt-2">
              配置条件以决定分支路径，例如“IF query 包含 ‘成功’”。<br />
              True 分支对应右侧上输出点，False 分支对应右侧下输出点。
            </p>
          </>
        );
      case 'code':
        return (
          <>
            <label className="block mb-2 text-sm font-medium text-gray-700">函数参数 (输入变量):</label>
            <div className="p-2 border border-dashed border-gray-300 rounded-md mb-3">
              {Object.entries(inputVariables).map(([key, value]) => (
                <div key={key} className="flex items-center gap-2 mb-2 bg-gray-50 p-2 rounded">
                  <span className="font-mono text-sm font-semibold">{key}</span>
                  <span className="text-gray-500">=</span>
                  <select
                    value={value}
                    onChange={(e) => handleUpstreamVarChange(key, e.target.value)}
                    className="flex-1 p-2 border border-gray-300 rounded-md"
                  >
                    <option value="">选择上游变量</option>
                    {previousOutputVars.map((varName, index) => (
                      <option key={index} value={varName}>{varName}</option>
                    ))}
                  </select>
                  <button
                    onClick={() => removeCodeInputVariable(key)}
                    className="px-2 py-1 bg-red-500 text-white text-xs rounded-md hover:bg-red-600 shrink-0"
                  >
                    删除
                  </button>
                </div>
              ))}
              <div className="flex gap-2 mt-2 border-t pt-2">
                <input
                  type="text"
                  value={newVarName}
                  onChange={(e) => setNewVarName(e.target.value)}
                  className="flex-1 p-2 border border-gray-300 rounded-md"
                  placeholder="新参数名"
                />
                <button
                  onClick={addCodeInputVariable}
                  className="px-3 py-1 bg-blue-500 text-white rounded-md hover:bg-blue-600 shrink-0"
                >
                  添加参数
                </button>
              </div>
            </div>
            <label className="block mb-2 text-sm font-medium text-gray-700">函数体 (Python):</label>
            <textarea
              name="code"
              value={nodeData.code || ""}
              onChange={handleChange}
              className="w-full p-2 border border-gray-300 rounded-md font-mono"
              placeholder={`# 你的 Python 代码, 例如:\n# result = var1 + var2\n# return result`}
              rows="10"
            />
            <p className="text-xs text-gray-500 mt-2">
              请在此处提供一个完整的 Python 函数定义。函数名可以任意指定。您在上方定义的“本地参数名”将作为参数传递给此函数，因此请确保函数签名中的参数名与之一一对应。<br />
              函数必须包含 `return` 语句，其返回值将作为此节点的输出。
            </p>
          </>
        );
      case 'http':
        return (
          <>
            <label className="block mb-2 text-sm font-medium text-gray-700">方法:</label>
            <select
              name="method"
              value={nodeData.method || 'GET'}
              onChange={handleChange}
              className="w-full p-2 border border-gray-300 rounded-md"
            >
              <option value="GET">GET</option>
              <option value="POST">POST</option>
              <option value="PUT">PUT</option>
              <option value="DELETE">DELETE</option>
            </select>
            <label className="block mt-3 mb-2 text-sm font-medium text-gray-700">URL:</label>
            <input
              type="text"
              name="url"
              value={nodeData.url || ''}
              onChange={handleChange}
              className="w-full p-2 border border-gray-300 rounded-md"
              placeholder="例如: https://api.example.com/data"
            />
            <label className="block mt-3 mb-2 text-sm font-medium text-gray-700">Headers:</label>
            {Object.entries(headers).map(([key, value]) => (
              <div key={key} className="flex gap-2 mb-2">
                <input
                  type="text"
                  value={key}
                  onChange={(e) => {
                    const newHeaders = { ...headers };
                    delete newHeaders[key];
                    newHeaders[e.target.value] = value;
                    setHeaders(newHeaders);
                  }}
                  className="w-1/3 p-2 border border-gray-300 rounded-md"
                  placeholder="Key"
                />
                <input
                  type="text"
                  value={value}
                  onChange={(e) => {
                    const newHeaders = { ...headers };
                    newHeaders[key] = e.target.value;
                    setHeaders(newHeaders);
                  }}
                  className="w-1/3 p-2 border border-gray-300 rounded-md"
                  placeholder="Value"
                />
                <button
                  onClick={() => removeHeader(key)}
                  className="px-2 py-1 bg-red-500 text-white rounded-md hover:bg-red-600"
                >
                  删除
                </button>
              </div>
            ))}
            <div className="flex gap-2 mb-2">
              <input
                type="text"
                value={newHeaderKey}
                onChange={handleKeyChange}
                className="w-1/3 p-2 border border-gray-300 rounded-md"
                placeholder="新 Key"
                list="header-keys"
              />
              <datalist id="header-keys">
                <option value="Content-Type" />
                <option value="Authorization" />
                <option value="Accept" />
                <option value="User-Agent" />
              </datalist>
              <input
                type="text"
                value={newHeaderValue}
                onChange={handleValueChange}
                className="w-1/3 p-2 border border-gray-300 rounded-md"
                placeholder="新 Value"
              />
              <button
                onClick={addHeader}
                className="px-2 py-1 bg-green-500 text-white rounded-md hover:bg-green-600"
              >
                添加
              </button>
            </div>
            <label className="block mt-3 mb-2 text-sm font-medium text-gray-700">Body/Params (JSON 字符串或 URL-encoded):</label>
            <textarea
              name="data"
              value={nodeData.data || ''}
              onChange={handleChange}
              className="w-full p-2 border border-gray-300 rounded-md font-mono"
              placeholder='例如: {"key": "value"} 或 param1=value1¶m2=value2'
              rows="5"
            />
          </>
        );
      case 'knowledge':
        return (
          <>
            <label className="block mt-3 mb-2 text-sm font-medium text-gray-700">查询变量:</label>
            <select
              name="query_variable"
              value={nodeData.query_variable || ''}
              onChange={handleChange}
              className="w-full p-2 border border-gray-300 rounded-md"
            >
              <option value="">选择上游输出变量作为查询</option>
              {previousOutputVars.map((varName) => (
                <option key={varName} value={varName}>
                  {varName}
                </option>
              ))}
            </select>
            <label className="block mt-3 mb-2 text-sm font-medium text-gray-700">知识库:</label>
            <select
              name="knowledge_base_id"
              value={nodeData.knowledge_base_id || ''}
              onChange={handleKnowledgeBaseChange}
              className="w-full p-2 border border-gray-300 rounded-md"
            >
              <option value="">选择一个知识库</option>
              {knowledgeBases.length > 0 ? (
                knowledgeBases.map((kb) => (
                  <option key={kb.id} value={kb.id}>
                    {kb.name}
                  </option>
                ))
              ) : (
                <option value="" disabled>无可用知识库</option>
              )}
            </select>
            <label className="block mt-3 mb-2 text-sm font-medium text-gray-700">返回结果数 (Top K):</label>
            <input
              type="number"
              name="top_k"
              value={nodeData.top_k || 3}
              onChange={handleChange}
              className="w-full p-2 border border-gray-300 rounded-md"
              min="1"
            />
            <label className="block mt-3 mb-2 text-sm font-medium text-gray-700">相似度阈值 (Score Threshold):</label>
            <input
              type="number"
              name="score_threshold"
              value={nodeData.score_threshold || 0.2}
              onChange={handleChange}
              className="w-full p-2 border border-gray-300 rounded-md"
              min="0"
              max="1"
              step="0.01"
            />
            <p className="text-xs text-gray-500 mt-1">
              只返回相似度分数大于等于此值的文档 (0.0 到 1.0)。
            </p>
          </>
        );
      default:
        return <p className="text-sm text-gray-600">该节点类型没有特定可配置的属性。</p>;
    }
  };

  return (
    <div className="modal-overlay" onClick={closeModal}>
      <div className="modal-content" onClick={(e) => e.stopPropagation()}>
        <h3 className="text-lg font-semibold mb-4">节点属性</h3>
        <label className="block mb-2 text-sm font-medium text-gray-700">节点名称:</label>
        <input
          type="text"
          name="name"
          value={nodeName}
          onChange={handleNameChange}
          className="w-full p-2 border border-gray-300 rounded-md"
        />
        <label className="block mt-3 mb-2 text-sm font-medium text-gray-700">输出变量:</label>
        <input
          type="text"
          value={outputVar}
          readOnly
          className="w-full p-2 border border-gray-300 rounded-md bg-gray-100"
        />
        {renderNodeSpecificFields()}
        <div className="mt-4 flex gap-3">
          <button
            onClick={handleSubmit}
            className="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600"
          >
            保存属性
          </button>
          <button
            onClick={handleDelete}
            className="px-4 py-2 bg-red-500 text-white rounded-md hover:bg-red-600"
          >
            删除节点
          </button>
          <button
            onClick={closeModal}
            className="px-4 py-2 bg-gray-500 text-white rounded-md hover:bg-gray-600"
          >
            关闭
          </button>
        </div>
        <p className="mt-4 text-xs text-gray-500">
          请在修改属性后点击“保存属性”按钮，然后点击“运行工作流”查看效果。
        </p>
      </div>
    </div>
  );
}

export default NodeModal;